package com.cml.dm.admin.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.cml.dm.admin.entity.DmExeLogger;
import com.cml.dm.admin.entity.DmMetadata;
import com.cml.dm.admin.model.DownloadModel;
import com.cml.dm.admin.request.BackupListParams;
import com.cml.dm.admin.service.DmEngineService;
import com.cml.dm.admin.service.EncryptionFactory;
import com.cml.dm.admin.service.FileCompressFactory;
import com.cml.dm.admin.service.impl.SM4Encryption;
import com.cml.dm.admin.util.ResponseData;
import com.cml.dm.admin.util.SuccessResponseData;
import com.cml.dm.engine.exception.DMException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController()
@RequestMapping("/dm")
@Slf4j
public class DmEngineController {
    @Autowired
    private DmEngineService dmEngineService;

    @GetMapping("/backup")
    public ResponseData backup(String taskID,String orgId, @RequestParam(required = false) String shardingColumn){
        dmEngineService.backup(taskID,orgId,shardingColumn);
        return new SuccessResponseData();
    }

    @GetMapping("/getTaskList")
    public ResponseData getTaskList(String taskID,String orgId){
        return new SuccessResponseData(dmEngineService.getTaskList(taskID,orgId));
    }

    /**
     * 备份列表
     * @param params
     * @return
     */
    @PostMapping("/backupList")
    public ResponseData backupList(@RequestBody(required = false) BackupListParams params){
        List<DmExeLogger> list = dmEngineService.backupList(params);
        return ResponseData.success(list);
    }

    //备份文件下载
    @GetMapping("download")
    public void download(@RequestParam(value = "id")Long id, HttpServletResponse response){
        DownloadModel model = dmEngineService.download(id);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename="+model.getFileName());
        response.addHeader("Content-Length", "" + model.getData().length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        try {
            response.getOutputStream().write(model.getData());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("下载文件失败:",e);
            throw new DMException("下载文件失败");
        }
    }


    @GetMapping("/recover")
    public ResponseData recover(Long id){
        dmEngineService.recover(id);
        return ResponseData.success();
    }

    @GetMapping("/testInsert")
    public ResponseData testInsert(Long orgId){
        List<DmMetadata> metadatas = new ArrayList<>();
        for (int i=0; i<2;i++){
            DmMetadata metadata = new DmMetadata();
            metadata.setNext("A"+i);
            metadata.setJoinNodeId("A"+i);
            metadata.setTable("A"+i);
            metadata.setNext("A"+i);
            metadata.setOrgId(orgId.toString());
            metadatas.add(metadata);
        }
        dmEngineService.saveBatch(metadatas);
        return ResponseData.success();
    }

    @GetMapping("/test")
    public ResponseData test(String name){
        FileInputStream fis = null;
        try {
            EncryptionFactory encryptionFactory = new SM4Encryption();
            fis = new FileInputStream("D:\\workspace\\data-mgr\\dm-core\\target\\classes\\backup\\"+name);
            int count = fis.available();
            while (count == 0){
                count = fis.available();
            }
            byte[] bytes = new byte[count];

            int readCount = 0; // 已经成功读取的字节的个数
            while (readCount < count) {
                readCount += fis.read(bytes, readCount, count - readCount);
            }
            byte[] deb = encryptionFactory.decode(bytes);
            String data = new String(deb);
            fis.close();
            return ResponseData.success(JSONObject.parseObject(data));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            IoUtil.close(fis);
        }
        return null;
    }

    @Autowired
    private FileCompressFactory fileCompressFactory;

    @GetMapping("/test1")
    public ResponseData test1(){
        FileInputStream fis = null;
        try {
            String path = "D:\\workspace\\data-mgr\\dm-core\\target\\classes\\backup\\test-614811626210807808-1671674537652.zip";
            File file = new File("D:\\workspace\\data-mgr\\dm-core\\target\\classes\\backup\\test-614811626210807808-1671674537652.zip");
//            fis = new FileInputStream(file);
            fileCompressFactory.uncompress(path);
            return ResponseData.success(path);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseData.success();
    }
}
